import { Component, ViewChild, Host, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';

//embedded components
import { RatingOverviewSummaryComponent } from './components/ratingOverview.component';
import { AnalystViewSummaryComponent } from './components/analystView.component';
import { KeyIssuesSummaryComponent } from './components/keyIssues.component';
import { SubIndustrySummaryComponent } from './components/subIndustry.component';
//Services
import { CompanyRiskRatingService } from '../companyRiskRating.service';
import { AppComponent } from '../../../../../app.component';
import { Subscription } from 'rxjs';
import { ClusterComponent } from '../../../riskCluster/cluster.component';
import { AnalyticsService } from '../../../../../shared/services/googleAnalytics.service';
import { GoogleAnalyticsBeacon } from '../../../../../shared/models/googleAnalytics.model';
import { CompanyService } from '../../company.service';
import { ResearchState } from '../../../research.service';

/**
 * Company risk summary component
 *
 * Author: Sorin Spiru
 * Date: 16.01.2018
 */
@Component({
  templateUrl: './summary.component.html',
  styleUrls: [
    '../../company.component.scss'
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CompanyRiskSummaryComponent extends ClusterComponent {
  private companySub: Subscription;

  public subPeerGroup: string;
  public isCore = false;
  public company: any;

  @ViewChild('ratingOverview') ratingOverview: RatingOverviewSummaryComponent;
  @ViewChild('analystView') analystView: AnalystViewSummaryComponent;
  @ViewChild('keyIssues') issues: KeyIssuesSummaryComponent;
  @ViewChild('subIndustry') subIndustry: SubIndustrySummaryComponent;

  constructor(
    @Host() private rootComponent: AppComponent,
    private cdRef: ChangeDetectorRef,
    private riskService: CompanyRiskRatingService,
    private analyticsService: AnalyticsService,
    private companyService: CompanyService
  ) {
    super(cdRef);
  }

  ngOnInit() {
    this.companyService.company.subscribe(data => {
      this.company = data;
      this.isCore = data.coreRiskResearchState === ResearchState.ResearchAvailable;

      this.companySub = this.riskService.company.subscribe((company) => {
        this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('ESG RR Overview', 'ESG Risk Rating', {CompanyId: company.id}));
        this.subPeerGroup = company.subPeerGroup;
        this.cdRef.markForCheck();
      });
    });
  }

  ngAfterViewInit() {
    Promise.all([this.ratingOverview.loaded, this.analystView.loaded/*, this.issues.loaded, this.subIndustry.loaded*/]).then(() => {
      this.rootComponent.finishLoading();
    });
  }

  ngOnDestroy() {
    this.companySub.unsubscribe();
  }
}